import os

import requests
import json

openkey = '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'


def generate_texts(prompt):
    """生成文本"""
    url = 'https://api.openai.com/v1/chat/completions'
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {openkey}"
    }
    # 具体请求目标
    data = {
        "model": "gpt-3.5-turbo",
        # 此部分使用f 可以进行拼接话术
        "messages": [{"role": "user", "content": f"{prompt}"}]
    }
    response = requests.post(url, headers=headers, json=data)
    response_text = json.loads(response.text)
    output = content = response_text['choices'][0]['message']['content']
    # print("-----------------------")
    # 打印相应
    print(response_text)
    print("-----------------------")
    print(output)
    return output


def generate_append_texts(prompt, txt):
    """文本继续写"""
    url = 'https://api.openai.com/v1/chat/completions'
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {openkey}"
    }
    # 具体请求目标
    data = {
        "model": "text-davinci-edit-001",
        "input": f"{prompt}",
        "instruction": f"{txt}",
    }
    response = requests.post(url, headers=headers, json=data)
    response_text = json.loads(response.text)
    # output = response_text['choices'][0]['message']['content']
    # print("-----------------------")
    # 打印相应
    # print(response_text)
    print("-----------------------")
    print(response_text)
    return response_text


def generate_images(prompt):
    """生成图片"""
    url = 'https://api.openai.com/v1/images/generations'
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {openkey}"
    }
    data = {
        # 提示词
        "prompt": f"{prompt}",
        # 数量
        "n": 2,
        # 图片大小
        "size": "1024x1024"
    }
    # 发送请求 拼接请求内容
    response = requests.post(url, headers=headers, json=data)
    response_text = json.loads(response.text)
    response_data = response_text['data']
    urls = [data['url'] for data in response_data]
    print(urls[0])
    print('------------------')
    # 发送请求，获取图片数据
    # response = requests.get(urls[0])
    # print(f"response image {response}")
    # 创建文件夹
    # os.makedirs('img', exist_ok=True)
    # 保存到本地
    # num = 0
    # for image in urls:
    #     response = requests.get(image)
    #     num += 1
    #     with open(f'img/{num}.png', 'wb') as f:
    #         f.write(response.content)
    # print(response_text)
    # for imgurl in response_text['data']:
    #     url = imgurl['url']
    #     print(url)
    return response_text

# 调用内容 提出问题 这部分其实是所有业务的核心
# generate_texts("把 The domain 163.com has been blocked. 翻译成中文")
# generate_images('一只黑色蓝眼睛的小猫')

generate_append_texts("小猫",'写一篇武侠小说')